package com.dyz.wsw.security.repository.impl;

import com.dyz.wsw.common.pojo.cache.UserCachePO;
import com.dyz.wsw.security.config.WswSecurityJWTProperties;
import com.dyz.wsw.security.repository.WswSecurityCacheRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Mono;

import java.time.Duration;
/**
 * 处理用户缓存数据的存储库实现类
 * @author dyz
 * @date 2025/2/9 19:08
 */
@Repository
@Slf4j
public class
WswSecurityCacheRepositoryImpl implements WswSecurityCacheRepository {

    private final WswSecurityJWTProperties properties;

    private final ReactiveRedisTemplate<String,Object> template;


    public WswSecurityCacheRepositoryImpl(
            WswSecurityJWTProperties properties,
            ReactiveRedisTemplate<String,Object> template
    ){
        log.debug("创建redis存储库对象: IUserCacheRepositoryImpl");
        this.properties = properties;
        this.template = template;
    }

    @Override
    public Mono<Long> deleteUserState(Long userId) {
        log.debug("开始处理【从缓存中删除用户信息】的数据访问,用户id: {}",userId);
        String key = KEY_PREFIX_USER_STATE + userId;
        return template.delete(key);
    }

    @Override
    public Mono<UserCachePO> getUserState(Long userId) {
        log.debug("开始处理【从缓存中读取用户信息】的数据访问,用户id: {}",userId);
        String key = KEY_PREFIX_USER_STATE + userId;
        return Mono.zip(template.opsForHash().get(key, HASH_KEY_USER_ENABLE), template.opsForHash().get(key, HASH_KEY_AUTH_STRING))
                .map(result-> new UserCachePO(Integer.parseInt(result.getT1().toString()),result.getT2().toString()));
    }


    @Override
    public Mono<Boolean> renewal(Long userId) {
        log.debug("开始处理【续期缓存中的用户信息】的数据访问,用户ID: {}，", userId);
        String key = KEY_PREFIX_USER_STATE + userId;

        return template.expire(key,Duration.ofMinutes(properties.getJwtExpiredTime()));
    }
}
